package Domostroy::Config;
use strict;
use strict 'refs';
use warnings;
use utf8;
use v5.10;

# comments #

require Exporter;
use vars qw($VERSION @ISA );

@ISA=qw(Exporter);
$VERSION = '0.02';

use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Domostroy::Utilites;

sub new {
	my ($class, %args) = @_;
	my $self = {};
	bless $self, ref $class || $class;
	return $self;
}

sub env {
  my ($self) = @_;
	print `rm -f /tmp/env.log`;
	my %result = getConfig("$ENV{'DOCUMENT_ROOT'}/config/main.conf");
	$result{'DBH'} = qq~$result{'DSN'},$result{'USER'},$result{'PASSWORD'},{RaiseError=>1,PrintError=>1,AutoCommit=>1}~;	
  return \%result;
}

sub getConfig {
	my $config = shift;
	my %result;
	open CONFIG, "<$config" or die($!);
	while (<CONFIG>) {
		my $str = &clearStr($_);
		if ( /^include/ ) {
			%result = (%result,&getInclude($_));
		} else {
			my ($key, $value) = split(/\s*=\s*/, $_, 2);
			$result{uc $key} = $value;
		}
	}
	close CONFIG;
	return %result;
}

sub clearStr {
	my $str = shift;
	chomp;               # Убрать перевод строки
	s/#.*|^\s+|\s+$//;   # Убрать лишнее
	next unless length;  # Что-нибудь осталось?
	return $str;
}

sub getInclude {
	my $include = shift; my %result;
	$include =~ s/^include|\s//g;
	my $config = &clearStr($include);
	my %include = &getConfig("$ENV{'DOCUMENT_ROOT'}/config/$config");
	my @keys = split(/\//,$config);
	my $key = pop @keys; 
	while ( my ($k,$v) = each %include ) {
		$result{uc $key}{$k} = $v;
	}
	return %result;
}

1;